<?php
namespace app\admin\controller;

use app\common\helper\Uploader;
use app\common\model\project_model\SystemMusicModel;
use app\common\model\project_model\BlessingModel;
use app\common\model\project_model\BlessingCategoryModel;
use app\yxwadmin\controller\Admin;
use app\admin\model\validate\Blessing as ValidateBlessing;

class Blessing extends Admin
{

    public $error_msg = '';

    /**
     * 首页
     * @return string
     * @throws \think\Exception
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 初始化表格
     * 关键字搜索
     * 分页
     * @throws
     * @return mixed
     */
    public function getList()
    {
        $limit = input('limit','0');
        $offset = input('offset','0');
        $sortName = input('sortName','id');
        $sortOrder = input('sortOrder','desc');
        $keyword = input('keywords','');

        $model = new BlessingModel();
        if ($keyword) {
            $count = $model->where('title|content|share_title|cate_name', 'like', '%' . $keyword . '%')->count();
            $list = $model
               ->where('title|content|share_title|cate_name', 'like', '%' . $keyword . '%')
               ->order([$sortName => $sortOrder])
               ->limit($offset . ',' . $limit)
               ->select();
        } else {
            $count = $model->count(); //查询满足要求的总记录数
            $list = $model
                ->order(array($sortName=>$sortOrder))
                ->limit($offset.','.$limit)
                ->select();
        }

        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function add() {
        if (request()->isPost()) {
            $validate = new ValidateBlessing();
            $data = $_REQUEST;
            $data['created_time'] = date('Y-m-d H:i:s', time());
            $data['updated_time'] = date('Y-m-d H:i:s', time());

            $res = $validate->check($data);
            if (!$res) {
                $this->error_msg = $validate->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }

            try{ // 祝福内容处理包括图片替换和上传七牛云
                $data['content'] = $this->dealImages($data['content']);
            }catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]);
            }

            $model = new BlessingModel($data);
            $res = $model->allowField(true)->save();
            if (!$res) {
                $this->error_msg = $model->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }
            return json(['code' => 1, 'msg' => '新增成功', 'data' => null]);

        } else {
            $this->assign('music_list', SystemMusicModel::musicList());
            $this->assign('status_list', BlessingModel::statusList());
            $this->assign('category_list', BlessingCategoryModel::categoryList());
            return $this->fetch();
        }
    }

    public function edit() {
        $id = $_REQUEST['id'];
        $model = new BlessingModel();

        if (request()->isPost()) {
            $validate = new ValidateBlessing();
            $data = $_REQUEST;
            $data['updated_time'] = date('Y-m-d H:i:s', time());
            $res = $validate->check($data);
            if (!$res) {
                $this->error_msg = $validate->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }

            try{ // 祝福内容处理包括图片替换和上传七牛云
                $data['content'] = $this->dealImages($data['content']);
                //$data['content'] = str_replace(chr(32),'&nbsp;',htmlspecialchars($this->dealImages($data['content'])));
            }catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]);
            }

            $res = $model->allowField(true)->save($data,['id' => $id]);
            if (!$res) {
                $this->error_msg = $model->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }

            return json(['code' => 1, 'msg' => '编辑成功', 'data' => null]);

        } else {
            $this->assign('music_list', SystemMusicModel::musicList());
            $this->assign('status_list', BlessingModel::statusList());
            $this->assign('category_list', BlessingCategoryModel::categoryList());
            $Rs = $model->where(['id' => $id])->find();
            $this->assign('Rs', $Rs);
            return $this->fetch();
        }
    }

    public function view() {
        $id = input('id/d');
        $model = new BlessingModel();
        $Rs = $model->where(['id' => $id])->find();
        $this->assign('Rs', $Rs);
        return $this->fetch();
    }

    // 预览
    public function prev_view() {
        $this->view->engine->layout(false);
        $model = new BlessingModel();
        $id = input('id/d');
        $this->assign('id', $id);
        $data = $model->where(['id' => $id])->find();
        //$content = str_replace('&nbsp;', chr(32), htmlspecialchars_decode($data['content']));
        $this->assign('contents', $data['content']);
        //var_dump($content);die;
        $this->assign('title', $data['title']);
        return $this->fetch('prev_view');
    }

    /**
     * 锁定
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function lock()
    {
        $id = input('id/d');
        $model = new BlessingModel();
        $where = ['id'=>$id];
        $data = $model->where($where)->find();
        $status = BlessingModel::STATUS_LOCK;
        if ($data['status'] == BlessingModel::STATUS_LOCK) {
            $status = BlessingModel::STATUS_OK;
        }
        $res = $model->save(['status' => $status], $where);
        if ($res) {
            $ret['code']=1;
            $ret['msg']='操作成功';
        } else {
            $ret['code']=0;
            $ret['msg']='服务器繁忙';
        }
        return json($ret);
    }

    /**
     * 对祝福内容的图片进行处理
     * @param $string
     * @return mixed
     * @throws \Exception
     */
    private function dealImages($string)
    {
        // 非背景图片替换
        $pattern = '<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""\']?[\s\t\r\n//]*(?<imgUrl>[^\s\t\r\n""\'<>]*)[^<>]*?/?[\s\t\r\n]*>';
        $string = $this->replaceImage($pattern, $string);
        // 背景图片替换
        $pattern = '|background-image:[\s]*url\((.+)?\);|Ui';
        $string = $this->replaceImage($pattern, $string);
        return $string;
    }

    /**
     * 上传并替换图片
     *
     * @param string $pattern 匹配模式
     * @param string $string 目标字符串
     * @return mixed
     * @throws \Exception
     */
    private function replaceImage($pattern, $string)
    {
        preg_match_all($pattern, $string, $matches);
        $arr = $this->clearQuote($matches[1]);
        foreach ($arr as $key => $item) {
            $res = $this->uploadQiNiu($item);
            if (!$res) {
                throw new \Exception('图片上传失败！');
            }
            $string = str_replace($matches[1][$key], $res, $string);
        }
        return $string;
    }

    /**
     * 去除空格
     * @param $inarr3
     * @return array
     */
    private function clearQuote($inarr3)
    {
        $list = [];
        foreach ($inarr3 as $index => $item) {
            $list[$index] = str_replace(['&quot;', '&amp;quot;'], ['', ''], $item);
        }
        return $list;
    }

    // 上传处理
    private function uploadQiNiu($image)
    {
        $pos = strpos($image, 'http', 0);
        $base_pos = strpos($image, 'data:image/', 0);
        if ($pos === 0) {
            $res = $this->remoteUpload($image); // 远程上传
        } else if ($base_pos === 0) {
            $res = $this->saveBase64($image); // base64上传
        } else {
            $filePath = str_replace('\\', '/', dirname(THINK_PATH) . '/' . $image);
            $res = $this->localUpload($filePath);// 默认本地上传
        }
        return $res;
    }

    private function saveBase64($base64, $key = NULL)
    {
        $uploader = new Uploader();
        if ($res = $uploader->uploadBase64($base64, $key)) {
            return $res;
        }
        return false;
    }

    private function remoteUpload($image_url)
    {
        $uploader = new Uploader();
        if ($res = $uploader->uploadFromRemote($image_url, 'photo_album_bless_' . time() . rand(101, 18989))) {
            return $res;
        }
        return false;
    }

    private function localUpload($image)
    {
        $uploader = new Uploader();
        if ($res = $uploader->uploadQiniu($image)) {
            return $res;
        }
        return false;
    }

}